package com.nuoniu.sibanyun.mapper.crm;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.nuoniu.sibanyun.annotation.DataAuth;
import com.nuoniu.sibanyun.entity.crm.CrmTouch;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 联系记录 Mapper 接口
 * </p>
 *
 * @author baiqiang
 * @since 2020-06-15
 */
@Component
@Mapper
public interface CrmTouchMapper extends BaseMapper<CrmTouch> {

    /**
     * 修改所属客户
     * @author 小啊刚
     * @date 2020/6/22
     */
    @Update("update crm_touch set crm_id = #{newCrmId}, crm_name = #{crmName}, update_user_id = #{userId}, update_user_name = #{realName}, update_date = now() where crm_id = #{crmId}")
    void updateCrmId(Integer crmId, Integer newCrmId, String crmName, Integer userId, String realName);

    /**
     * 修改业务人员
     * @author 小啊刚
     * @date 2020-08-14
     */
    @Update("update crm_touch set sales_man_name = #{realName} where sales_man_id = #{id}")
    void updateSalesMan(Long id, String realName);

    /**
     * 获取超过联系时间的数量
     * @author 小啊刚
     * @date 2021-07-31
     */
    @Select("select count(1) from crm_touch where #{contactDate} >= (select max(contact_date) from crm_touch where company_id=#{companyId} and status=0) and company_id=#{companyId}")
    Integer getMaxTouchCount(LocalDateTime contactDate, Integer companyId);

    @DataAuth(tableAlias = "crm",personalField = "collar_user_id",companyField = "company_id",officeField = "office_id")
    Page<CrmTouch> pageList(Page page, @Param("touch") CrmTouch touch);

    /**
     * 根据联系人获取
     * @author 小啊刚
     * @date 2021-11-10
     */
    @Select("select * from crm_touch where link_man_id=#{id} and status=0")
    List<CrmTouch> getByLinkManId(String id);

    /**
     * 根据下次联系时间获取
     * @author 小啊刚
     * @date 2022-01-12
     */
    @Select("SELECT * FROM crm_touch where date(next_touch_date) >= date(now()) and date(next_touch_date) <= DATE_ADD(now(), INTERVAL 3 DAY)")
    List<CrmTouch> getListByNextTouchDate();
}
